package com.ibiaoke.system.service;

import com.ibiaoke.common.consts.CommonConsts;
import com.ibiaoke.common.exception.ServiceException;
import com.ibiaoke.common.utils.*;
import com.ibiaoke.system.constant.ShopConstant;
import com.ibiaoke.system.dao.ShopDao;
import com.ibiaoke.system.entity.Shop;
import com.ibiaoke.system.entity.ShopExample;
import com.ibiaoke.system.entity.dto.DeliverInfoDTO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * Created by SuXin on 2017/6/20.
 */
@Service("shopService")
public class ShopServiceImpl implements ShopService {

    //免配送费距离
    public static final int FREE_DISTANCE = 100;
    //基础配送范围
    public static final int START_RANG = 3000;
    //基础配送费
    public static final BigDecimal BASE_DELIVERY_PRICE = new BigDecimal(5);
    //超出基础配送范围每公里附加费（单位元）
    public static final BigDecimal OUT_RANG_COST = new BigDecimal(2);
    //最远配送范围
    public static final int MAX_DELIVERY_RANG = 3000;
    //满金额免基础配送费
    public static final BigDecimal FULL_FREE_BASE_PRICE = new BigDecimal(49);

    @Autowired
    private ShopDao shopDao;

    /**
     * 插入店铺信息
     *
     * @param shop
     * @return
     */
    @Override
    public int saveShop(Shop shop) {
        AssertUtils.notBlank(shop.getShopName(), "店铺名不能为空");

        AssertUtils.notBlank(shop.getShopAddress(), "地址不能为空");

        AssertUtils.requireTrue(ValidateUtils.isMobile(shop.getShopMobile()), "手机号码错误");

        AssertUtils.notBlank(shop.getContactPerson(), "联系人不能为空");

        AssertUtils.notBlank(shop.getProvinceId(), "省份Id不能为空");

        AssertUtils.notBlank(shop.getCityId(), "城市Id不能为空");

        AssertUtils.notBlank(shop.getCountyId(), "区县Id不能为空");

        shop.setCheckStatus((byte) ShopConstant.NOTAUDITED);
        shop.setDelFlag((byte) CommonConsts.NO);
        shop.setCreateTime(new Date());
        return shopDao.insertSelective(shop);
    }

    /**
     * 更新店铺信息
     *
     * @param shop
     * @return
     */
    @Override
    public int updateShop(Shop shop) {
        AssertUtils.notNull(shop.getShopId(), "店铺Id不能为空");

        AssertUtils.notBlank(shop.getShopName(), "店铺名不能为空");

        AssertUtils.notBlank(shop.getShopAddress(), "地址不能为空");

        AssertUtils.notBlank(shop.getShopMobile(), "联系电话不能为空");

        AssertUtils.notBlank(shop.getContactPerson(), "联系人不能为空");

        AssertUtils.notBlank(shop.getProvinceId(), "省份Id不能为空");

        AssertUtils.notBlank(shop.getCityId(), "城市Id不能为空");

        AssertUtils.notBlank(shop.getCountyId(), "区县Id不能为空");

        return shopDao.updateByPrimaryKeySelective(shop);
    }

    /**
     * 获取店铺详细信息
     */
    @Override
    public Shop getShop(Integer shopId) {
        AssertUtils.notNull(shopId, "店铺Id不能为空");
        Shop shop = shopDao.getShopByShopId(shopId);
        AssertUtils.notNull(shop, "店铺不存在");
        return shop;
    }

    /**
     * 获取店铺列表
     */
    @Override
    public List<Shop> listShop() {
        return shopDao.listShop();
    }

    /**
     * 逻辑删除店铺
     */
    @Override
    public int deleteShop(Integer shopId) {
        AssertUtils.notNull(shopId, "店铺Id不能为空");
        Shop shop = new Shop();
        shop.setShopId(shopId);
        shop.setDelFlag((byte) CommonConsts.YES);
        return shopDao.updateByPrimaryKeySelective(shop);
    }

    @Override
    public List<Shop> listAllShop() {
        ShopExample shopExample = new ShopExample();
        shopExample.createCriteria().andDelFlagEqualTo((byte) 0);
        return shopDao.selectByExample(shopExample);
    }

    @Override
    public List<Shop> listSortedShops(final Double longitude, final Double latitude) {
        if (longitude == null || latitude == null) {
            throw new ServiceException("经纬度不能为空");
        }
        List<Shop> allShop = listAllShop();
        if (CollectionUtils.isNotEmpty(allShop)) {
            Collections.sort(allShop, (o1, o2) -> {
                boolean o1Max = (o1 == null || o1.getDesLongitude() == null || o1.getDesLatitude() == null);
                boolean o2Max = (o2 == null || o2.getDesLongitude() == null || o2.getDesLatitude() == null);
                if (o1Max && o2Max) {
                    return 0;
                }
                if (o1Max) {
                    return 1;
                }
                if (o2Max) {
                    return -1;
                }
                Double distance1 = LocationUtils.getDistance(longitude, latitude, o1.getDesLongitude(), o1.getDesLatitude());
                Double distance2 = LocationUtils.getDistance(longitude, latitude, o2.getDesLongitude(), o2.getDesLatitude());
                return distance1.compareTo(distance2);
            });
        }
        return allShop;

    }

    /**
     * 获取最近的店铺
     *
     * @param longitude
     * @param latitude
     * @return
     */
    @Override
    public Shop getNearestShop(Double longitude, Double latitude) {
        List<Shop> shops = listSortedShops(longitude, latitude);
        return CollectionUtils.isEmpty(shops) ? null : shops.get(0);
    }


    /**
     * 验证时间、距离是否在配送范围
     *
     * @param longitude
     * @param latitude
     * @return
     */
    @Override
    public String validateDistanceAndOpenTime(Double longitude, Double latitude) {
        /**
         * 定位判断
         */
        if (longitude == null || latitude == null) {
            return "定位失败";
        }
        /**
         * 配送范围判断
         */
        Shop nearestShop = getNearestShop(longitude, latitude);
//        if (nearestShop != null) {
//            double distance = LocationUtils.getDistance(longitude, latitude, nearestShop.getDesLongitude(), nearestShop.getDesLatitude());
//            if (distance > MAX_DELIVERY_RANG) {
//                return "抱歉，超出配送范围啦";
//            }
//        }
        /**
         * 营业时间
         */
        boolean isRight = OpenTimeUtil.validateTime(nearestShop.getOpenBeginTime(), nearestShop.getOpenEndTime());
        if (!isRight) {
            return "不在营业时间，[" + nearestShop.getShopName() + "]营业时间("
                    + OpenTimeUtil.getOpenString(nearestShop.getOpenBeginTime(), nearestShop.getOpenEndTime()) + ")";
        }
        return null;
    }

    /**
     * 配送费计算
     * 1.订单满15元起送
     * 2.三公里范围内,配送费为4元
     * 3.若超出三公里范围(超出部分：一公里=2元)
     * 4.若超出距离不足一公里，以一公里计算，最远配送范围为十公里
     *
     * @param longitude
     * @param latitude
     * @param productPrice
     * @return
     */
    @Override
    public DeliverInfoDTO getDeliveryInfo(Double longitude, Double latitude, BigDecimal productPrice) {
        DeliverInfoDTO deliverInfoDTO = new DeliverInfoDTO();
       /* AssertUtils.notNull(longitude, "经度不能为空");
        AssertUtils.notNull(latitude, "纬度不能为空");
        AssertUtils.notNull(latitude, "商品金额不能为空");
        Shop nearestShop = getNearestShop(longitude, latitude);
        deliverInfoDTO.setShopId(nearestShop.getShopId());
        deliverInfoDTO.setShopName(nearestShop.getShopName());

        double distance = LocationUtils.getDistance(longitude, latitude, nearestShop.getDesLongitude(), nearestShop.getDesLatitude());
        deliverInfoDTO.setDistance(distance / 1000);

        BigDecimal charge = BigDecimal.ZERO;

        //超过基础配送范围额外加收配送费
        if (distance > START_RANG) {
            charge = getOutRangeDeliveryPrice(distance);
        }
        */


        /**
         * 新的业务逻辑，满49包邮，不满49元，加4元配送费
         *  2017/11/20
         */
        BigDecimal charge = BigDecimal.ZERO;
        AssertUtils.notNull(longitude, "经度不能为空");
        AssertUtils.notNull(latitude, "纬度不能为空");
        AssertUtils.notNull(productPrice, "商品金额不能为空");
        Shop nearestShop = getNearestShop(longitude, latitude);
        deliverInfoDTO.setShopId(nearestShop.getShopId());
        deliverInfoDTO.setShopName(nearestShop.getShopName());

        double distance = LocationUtils.getDistance(longitude, latitude, nearestShop.getDesLongitude(), nearestShop.getDesLatitude());
        deliverInfoDTO.setDistance(distance / 1000);
        if(productPrice.compareTo(FULL_FREE_BASE_PRICE) >= 0){
            charge = new BigDecimal(0);
        }else{
            charge = charge.add(BASE_DELIVERY_PRICE);
        }
        //100米内免基础配送费,满49免基础配送费
        boolean freeBaseDeliveryPrice = distance < FREE_DISTANCE || productPrice.compareTo(FULL_FREE_BASE_PRICE) >= 0;
        if (freeBaseDeliveryPrice) {
            charge = new BigDecimal(0);
        }
        deliverInfoDTO.setDeliveryPrice(charge);
        return deliverInfoDTO;
    }

    @Override
    public Shop getShop(String mobile) {
        AssertUtils.notBlank(mobile,"手机号码不能为空");
        ShopExample example =new ShopExample();
        example.createCriteria().andShopMobileEqualTo(mobile);
        return shopDao.getByExample(example);
    }

    @Override
    public int relevanceShop(Shop shop) {
        AssertUtils.notNull(shop.getUserId(),"用户id不能为空");
        AssertUtils.notNull(shop.getShopId(),"店铺id不能为空");
        return shopDao.relevanceShop(shop);
    }

    /**
     * 超过基础配送范围额外加收配送费
     *
     * @param distance
     * @return
     */
    private BigDecimal getOutRangeDeliveryPrice(double distance) {

        double outKm = (distance - START_RANG) / 1000.0;
        int outKmIntegerPart = (int) outKm;//超过公里整数部分
        double outKmDecimalPart = outKm - outKmIntegerPart;//超过公里小数部分
        //超过0.1公里按1公里算
        if (outKmDecimalPart > 0.1) {
            outKmIntegerPart += 1;
        }
        return OUT_RANG_COST.multiply(new BigDecimal(outKmIntegerPart));
    }


}
